package helper.base

object MemoryHelper {
    fun getUsedMemory(
        action: () -> Unit,
    ): Long {
        val runtime = Runtime.getRuntime()

        // 初始已使用内存 = 总内存 - 可用内存
        val initialUsedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024

        action()

        // 最终已使用内存 = 总内存 - 可用内存
        val finalUsedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024

        // 计算内存使用量
        val usedMemory = finalUsedMemory - initialUsedMemory

        println("Used memory: $usedMemory MB")
        return usedMemory
    }

    @JvmStatic
    fun main(args: Array<String>) {
        getUsedMemory {
            // 创建一个足够大的数组来消耗内存
            val bigArray = Array(1_000_000) { DoubleArray(50) }
        }
    }
}